var messageService = require('../../../logic/messageService');

module.exports = function(app) {
	return new Handler(app);
};

var Handler = function(app) {
		this.app = app;
};

var handler = Handler.prototype;

/**
 *
 * @param msg
 * @param session
 * @param next
 */
handler.login = function(msg, session, next) {
	var self = this;
	var uid = +msg.uid;
	var sessionService = self.app.get('sessionService');

	async.waterfall([
		function(cb) {
			sessionService.kick(uid, cb);
		}, function(cb) {
			session.bind(uid, cb);
		}, function(cb) {
			session.on('closed', onUserOffline.bind(null, self.app));

			var clientAddress = sessionService.getClientAddressBySessionId(session.id);
			if (clientAddress && clientAddress.ip) {
				var ip = clientAddress.ip;
				var ipv6Pos = ip.lastIndexOf("ffff:");
				if (ipv6Pos != -1) {
					ip = ip.slice(ipv6Pos + 5);
				}
				msg.ip = ip;
			}

			msg.sid = session.frontendId;
			cb();
		}
	], function(err) {
		if(err) {
			next(err, {code: Code.SYSTEM_ERROR});
			return;
		}

		self.app.rpc.world.userRemote.login(session, msg, function(code, openid, info) {
			if (code) {
				next(null, {code: code}); return;
			}

			session.set('openid', openid);
			session.pushAll();

			info.serverTime = new Date().getTime();

			next(null, info);
			logger.debug("uid=%d openid=%s login marks=%j", uid, openid, info.marks);
		});
	});
};

var onUserOffline = function(app, session) {
    if(!session || !session.uid) {
        return;
    }

	var uid = session.uid;
	logger.debug("uid=%d openid=%s offline", uid, session.get('openid'));
    app.rpc.world.userRemote.offline(session, uid, null);

    var rid = session.get('rid');
    if (rid) {
        app.rpc.game.userRemote.offline(session, uid, {rid: rid}, null);
    }
};

handler.heartbeat = function(msg, session, next) {
	next(null, {});
}

handler.test = function(msg, session, next) {
	//messageService.send({uid:session.uid, sid:session.frontendId}, "onConnectorTest0", {});
	messageService.send({uid:session.uid, sid:session.frontendId}, "onConnectorTest1", {
		stamp: (new Date()).getTime()
	});

	next(null, {stamp: (new Date()).getTime()});

	//messageService.send({uid:session.uid, sid:session.frontendId}, "onConnectorTest2", {});

	for (var i = 0; i < 50; ++i) {
		messageService.send({uid:session.uid, sid:session.frontendId}, "onConnectorTest3", {
			stamp: (new Date()).getTime()
		});
	}
}